/**
 * @description  券池审批
 * @author shenhong
 */
import React, { PureComponent } from 'react';
import { connect, routerRedux } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { message, Row, Col, Button, Modal } from 'antd';
import { ContentPackage, TableC, DATA_ENTRY, PrimaryC, ModalC, PrimaryGhostC, AdvancedSearch } from '../../../../comps';
import MyModal from '../tools/index';
import style from './index.less';
import _ from 'lodash';
import { stringify } from 'qs';
import { isZiGuanEvir, exportFile as exportFileFunc } from '../../../../utils/commonFunc';
@Form.create()
class CouponPoolApproval extends PureComponent {
  constructor() {
    super();
    this.state = {
      isVisible: false, // modal框是否可见
      formData: {}, // 表单的值
      type: '', // 操作类型
      id: '', // 点击修改/查看/出池时对应流程id
      disabled: false, // 是标的要素条目要素是否置灰
      isReset: false, // 是否重置
      currentUser: {}, // 用户信息
      sortedInfo: {}, // 排序信息
      exportQuery: undefined, //导出的入参
      isZiGuan: false,
      selectStatusZG: [
        { code: '1', value: '新建' },
        { code: '3', value: '已办结' },
      ],
    };
  }
  componentDidMount() {
    const { dispatch } = this.props;
    let temp = isZiGuanEvir();
    let isZiGuan = !!temp; // 判断该页面是在资管被引入的，还是maat
    this.setState({ isZiGuan });
    const {
      globalM: { dataDictionary = {} },
    } = this.props;
    dispatch({
      type: 'couponPoolApprovalM/save', // 获取字典值
      payload: {
        selectData: dataDictionary,
      },
    });
    dispatch({
      type: 'couponPoolApprovalM/getApplyPeople',
      payload: {},
    });
    dispatch({
      type: 'couponPoolApprovalM/findAll',
      payload: { pageSize: 20, currentSize: 1 },
    });
    dispatch({
      type: 'couponPoolApprovalM/getPoolName',
      payload: { pageSize: 20, currentSize: 1 },
    });
    this.setState({
      exportQuery: { pageSize: 20, currentSize: 1 },
    });
  }

  // 点击详细/编辑时触发方法
  edit = (e) => {
    const { dispatch } = this.props;
    // dispatch({
    //   type: 'couponPoolApprovalM/getDetails',
    //   payload: { id: e.id },
    //   callback: (res) => {
    //     // this.setState({ type: 'edit', id: e.id, disabled: true, isVisible: true, recordId: e.id })
    //   }
    // });
    this.setState({ type: 'edit', id: e.id, disabled: true, isVisible: true, recordId: e.id });
  };

  // 新增
  handleAdd = () => {
    this.setState({ isVisible: true, type: 'add', disabled: false });
  };

  // 查看详细
  seeData = (e) => {
    // this.props.dispatch({
    //   type: 'couponPoolApprovalM/getDetails',
    //   payload: { id: e.id },
    //   callback: (res) => {
    //     this.setState({ type: 'see', disabled: true, isVisible: true, recordId: e.id })
    //   }
    // });
    this.setState({ type: 'see', disabled: true, isVisible: true, recordId: e.id });
  };

  // 出池
  outPool = (e) => {
    this.props.dispatch({
      type: 'couponPoolApprovalM/getDetails',
      payload: { id: e.id },
      callback: (res) => {
        this.setState({
          type: 'outPool',
          disabled: true,
          isVisible: true,
          recordId: e.id,
        });
      },
    });
  };

  // 点击取消
  handleCancel = () => {
    if (this.state.type == 'see') {
      this.setState({ isVisible: false });
    } else {
      this.setState({ isVisible: false, isError: false, isOver: false, isError2: false }, () => {
        this.child.resetDatas();
      });
    }
  };

  // 判断标的是否有重复
  isBeing = (arr) => {
    var hash = {};
    for (var i in arr) {
      if (hash[arr[i]]) {
        return true;
      }
      hash[arr[i]] = true;
    }
    return false;
  };

  handleOk = (e) => {
    const { dispatch } = this.props;
    const data = this.child.getData();
    if (data == 'see') {
      this.setState({ isVisible: false });
    } else {
      if (data !== undefined) {
        if (data.inPoolWay == 'manual') {
          const query = data;
          query.type = e;

          if (this.state.type == 'edit') {
            query.id = this.state.id;
          }
          if (e == '0') {
            //  保存无需对标的做校验
            dispatch({
              type: 'couponPoolApprovalM/getAddAndEdit',
              payload: query,
              callback: (res) => {
                if (res.code == 0) {
                  this.setState({
                    exportQuery: { pageSize: 20, currentSize: 1 },
                  });
                  dispatch({
                    type: 'couponPoolApprovalM/findAll',
                    payload: { pageSize: 20, currentSize: 1 },
                  });
                  this.setState({ isVisible: false });
                }
              },
            });
          } else {
            dispatch({
              type: 'couponPoolApprovalM/checkAdd', // 发起之前需要对标的做校验
              payload: query,
              callback: (res) => {
                dispatch({
                  type: 'couponPoolApprovalM/getAddAndEdit',
                  payload: query,
                  callback: (res) => {
                    if (res.code == 0) {
                      dispatch({
                        type: 'couponPoolApprovalM/findAll',
                        payload: { pageSize: 20, currentSize: 1 },
                      });
                      this.setState({
                        exportQuery: { pageSize: 20, currentSize: 1 },
                      });
                      this.setState({ isVisible: false });
                    }
                  },
                });
              },
            });
          }
        } else {
          const query = data;
          query.type = e == '0' ? 'SAVE' : 'SAVE_AND_COMMIT';
          if (this.state.type == 'edit') {
            query.id = this.state.id;
          }
          dispatch({
            type: 'couponPoolApprovalM/autoAdd',
            payload: query,
            callback: (res) => {
              if (res.code == 0) {
                dispatch({
                  type: 'couponPoolApprovalM/findAll',
                  payload: { pageSize: 20, currentSize: 1 },
                });
                this.setState({
                  exportQuery: { pageSize: 20, currentSize: 1 },
                });
                this.setState({
                  isVisible: false,
                });
              }
            },
          });
        }
      }
    }
  };

  // 判断类型
  selectType = () => {
    const { type } = this.state;
    if (type == 'add') {
      const text = '新建';
      return text;
    } else if (type == 'edit') {
      const text = '编辑';
      return text;
    } else if (type == 'see') {
      const text = '查看';
      return text;
    } else if (type == 'outPool') {
      const text = '出池';
      return text;
    } else if (type == 'request') {
      const text = '重新发起';
      return text;
    }
  };

  // modal框
  showModal = () => {
    const {
      couponPoolApprovalM: { detailData },
      loading,
    } = this.props;
    const { type, isVisible } = this.state;
    const text = this.selectType(); // 根据不同类型展示不同的modal框名称
    const newProps = {
      visible: isVisible,
      title: `${text}`,
      width: 1300,
      footer:
        type == 'see'
          ? null
          : [
              <PrimaryGhostC key='footOne' onClick={this.handleCancel} title='取消' />,
              <PrimaryC key='save' onClick={() => this.handleOk('0')} style={{ marginLeft: '10px' }} loading={loading.effects['couponPoolApprovalM/getAddAndEdit']} title='保存' />,
              <PrimaryC
                key='commit'
                onClick={() => this.handleOk('1')}
                style={{ marginLeft: '10px' }}
                loading={loading.effects['couponPoolApprovalM/getAddAndEdit']}
                title='提交'
              />,
            ],
    };
    return (
      <div>
        {isVisible ? (
          <ModalC {...newProps} onCancel={this.handleCancel}>
            <MyModal
              defaultData={detailData} // 修改或查看时回填的数据
              type={type} // 是什么操作（新增，查看，编辑，出池，重新发起）
              onRef={(ref) => (this.child = ref)} // 父组件对本组件的引用
              recordId={this.state.recordId} // 根据流程id获取详细信息
            />
          </ModalC>
        ) : null}
      </div>
    );
  };

  // 表格改变事件
  tableChange = (pagination, filt, sorter) => {
    const { formData, isReset } = this.state;
    const { dispatch } = this.props;
    if (isReset) {
      message.warning('已重置查询条件，请重新查询');
    } else {
      this.setState(
        {
          sortedInfo: sorter,
        },
        () => {
          let query = _.cloneDeep(formData);
          if (formData.endTime) {
            query.endTime = formData.endTime.format('YYYY-MM-DD');
          }
          if (formData.startTime) {
            query.startTime = formData.startTime.format('YYYY-MM-DD');
          }
          query.pageSize = pagination.pageSize;
          query.currentPage = pagination.current;
          if (sorter.order !== undefined) {
            if (sorter.order == 'descend') {
              query.orderType = 'desc';
            } else if (sorter.order == 'ascend') {
              query.orderType = 'asc';
            } else {
              query.orderType = '';
            }
          } else {
            delete query.orderType;
          }
          this.setState({
            exportQuery: { ...query },
          });
          dispatch({
            type: 'couponPoolApprovalM/findAll',
            payload: query,
          });
        },
      );
    }
  };

  // 对表格里券池名称id转换
  changePoolName = (text, poolNameData) => {
    let tet = text;
    if (poolNameData && poolNameData.length) {
      poolNameData.map((item) => {
        if (item.id == text) {
          tet = item.name;
        }
      });
    }
    return tet;
  };

  // 转换流程状态
  changeFlowStatus = (text, arr) => {
    let tet = text;
    if (arr && arr.length) {
      arr.map((item) => {
        if (item.code == text) {
          tet = item.value;
        }
      });
    }
    return tet;
  };

  // 转换券池类型
  getPoolType = (text, arr) => {
    let tex = text;
    if (arr && arr.length) {
      arr.map((item) => {
        if (item.code == text) {
          tex = item.value;
        }
      });
    }
    return tex;
  };

  // 转换columns的格式需求
  changeColumns = (columns) => {
    const { sortedInfo } = this.state;
    const {
      couponPoolApprovalM: { poolNameData, selectData },
    } = this.props;
    let newColumns = columns;
    if (newColumns?.length && newColumns[newColumns.length - 1].title != '操作') {
      newColumns.push({
        title: '操作',
        dataIndex: 'id',
        key: 'id',
        type: 'operate',
        operates: [
          {
            title: '查看',
            onClick: (record) => this.seeData(record),
            rules: {
              hide: {
                relation: 'and',
                items: [{ key: 'flowState', value: ['1'], relation: ['='] }], //  已保存以外的都可查看
              },
            },
          },
          {
            title: '编辑',
            onClick: (record) => this.edit(record),
            rules: {
              hide: {
                relation: 'and',
                items: [{ key: 'flowState', value: ['1'], relation: ['!='] }], //  已保存以外均不可编辑
              },
            },
          },
          {
            title: '出池',
            onClick: (record, index) => this.outPool(record),
            rules: {
              hide: {
                relation: 'or',
                items: [
                  // 已办结 手动 入池的才可出池
                  { key: 'flowState', value: ['3'], relation: ['!='] }, // 3- 已办结
                  { key: 'inPoolWay', value: ['manual'], relation: ['!='] }, // manual- 手动
                  { key: 'direction', value: ['1'], relation: ['!='] },
                ], // 1-入池
              },
            },
          },
        ],
      });
    }
    if (newColumns && newColumns.length) {
      newColumns.map((item) => {
        if (item.key == 'securityId') {
          item.render = (text, record) => {
            return this.changePoolName(text, poolNameData);
          };
        } else if (item.key == 'flowState') {
          item.render = (text, record) => {
            return this.changeFlowStatus(text, this.state.isZiGuan ? this.state.selectStatusZG : selectData.FLOWSTATE);
          };
        } else if (item.key == 'inPoolWay') {
          item.render = (text, record) => {
            return text == 'manual' ? '手动入池' : '自动入池';
          };
        } else if (item.key == 'direction') {
          item.render = (text, record) => {
            return text == '1' ? '入池' : '出池';
          };
        } else if (item.key == 'launchTime') {
          item.sorter = true;
          item.sortOrder = sortedInfo.columnKey == 'launchTime' && sortedInfo.order;
        } else if (item.key == 'securityType') {
          item.render = (text, record) => {
            return this.getPoolType(text, selectData.SECURITYPOOL_ASSETCLASS);
          };
        }
      });
    }
    return newColumns;
  };

  // 跳转至自动入池监控页面
  changRouter = () => {
    this.props.dispatch(routerRedux.push(`/securityMnt/autoMonitor`));
  };
  exportFile = () => {
    const { exportQuery } = this.state;
    const obj = _.cloneDeep(exportQuery);
    obj.currentSize = 1; //导出不分页
    exportFileFunc('gateway/portfolio-server/flowSecurity/export', obj);
  };
  //渲染表格
  tableRender = () => {
    const {
      couponPoolApprovalM: { showData },
      loading,
    } = this.props;
    const { exportQuery, isZiGuan } = this.state;
    const tableData = showData.dataSource;
    const columns = this.changeColumns(showData.columns);
    const pageInfo = showData.pageInfo;
    return (
      <div style={{ marginTop: '10px' }}>
        <Row className={style.btn}>
          <Col span={12}>
            <PrimaryC onClick={this.handleAdd} title='新增'></PrimaryC>
            {!isZiGuan && (
              <a
                style={{ marginLeft: '10px' }}
                onClick={() => {
                  this.changRouter();
                }}
              >
                自动入池监控
              </a>
            )}
          </Col>
          <Col span={12}>
            <PrimaryGhostC title='导出' onClick={this.exportFile} style={{ marginBottom: '10px' }} disabled={exportQuery ? false : true} />
          </Col>
        </Row>
        <div style={{ marginTop: '10px' }}>
          <TableC
            columns={columns}
            loading={loading.effects['couponPoolApprovalM/findAll']}
            dataSource={tableData}
            current={pageInfo.currentPage === 0 ? 1 : pageInfo.currentPage}
            total={pageInfo.total}
            pageSize={pageInfo.numInPage}
            onChange={this.tableChange}
            selfScrollY={true}
            rowKey='id'
          />
        </div>
      </div>
    );
  };

  // 查询
  searchData = (e) => {
    const { formData } = this.state;
    const { dispatch } = this.props;
    let query = _.cloneDeep(formData);
    if (formData.endTime) {
      query.endTime = formData.endTime.format('YYYY-MM-DD');
    }
    if (formData.startTime) {
      query.startTime = formData.startTime.format('YYYY-MM-DD');
    }
    query.pageSize = 20;
    query.currentSize = 1;
    this.setState({
      exportQuery: { ...query },
    });
    dispatch({
      type: 'couponPoolApprovalM/findAll',
      payload: query,
    });
    this.setState({
      isReset: false,
    });
  };

  // 改变券池类型数据格式
  changeType = (arr) => {
    let data = [];
    if (arr && arr.length) {
      arr.map((item) => {
        data.push({ title: item.value, value: item.code });
      });
    }
    return data;
  };

  // 转换券池名称数据格式
  changeName = (e) => {
    let arr = [];
    if (e && e.length) {
      e.map((item) => {
        arr.push({ title: item.name, value: item.id });
      });
    }
    return arr;
  };

  // 转换申请人数据格式
  changeApply = (e) => {
    let data = [];
    if (e && e.length) {
      e.map((item) => {
        data.push({ title: item.name, value: item.userId });
      });
    }
    return data;
  };

  render() {
    const {
      couponPoolApprovalM: { poolNameData, selectData, applyData },
    } = this.props;
    const selectType = this.changeType(selectData.SECURITYPOOL_ASSETCLASS); //
    const selectStatus = this.changeType(this.state.isZiGuan ? this.state.selectStatusZG : selectData.FLOWSTATE);
    const selectInOut = this.changeType(selectData.FLOWDESCRIBE);
    const poolName = this.changeName(poolNameData);
    const selectApply = this.changeApply(applyData);
    const selectInpool = [
      { value: 'auto', title: '自动入池' },
      { value: 'manual', title: '手动入池' },
    ];
    const selectInpoolZG = [{ value: 'manual', title: '手动入池' }];
    const searchProps = {
      dataSource: [
        {
          dataIndex: 'flowName',
          title: '流程名称',
          type: DATA_ENTRY.INPUT,
          allowClear: true,
        },
        {
          dataIndex: 'securityName',
          title: '券池名称',
          type: DATA_ENTRY.SELECT,
          dataSource: poolName,
          allowClear: true,
          filterOption: (input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0,
        },
        {
          dataIndex: ['startTime', 'endTime'],
          title: '发起时间',
          type: DATA_ENTRY.RANGEDATE,
          onRef: (ref) => this.setState({ RANGEDATE: ref }),
        },
        {
          dataIndex: 'securityType',
          title: '券池类型',
          type: DATA_ENTRY.SELECT,
          dataSource: selectType,
          allowClear: true,
        },
        {
          dataIndex: 'flowState',
          title: '流程状态',
          type: DATA_ENTRY.SELECT,
          dataSource: selectStatus,
          allowClear: true,
        },
        {
          dataIndex: 'poolWay',
          title: '入池方式',
          type: DATA_ENTRY.SELECT,
          dataSource: this.state.isZiGuan ? selectInpoolZG : selectInpool,
          allowClear: true,
        },
        {
          dataIndex: 'direction',
          title: '操作方向',
          type: DATA_ENTRY.SELECT,
          dataSource: selectInOut,
          allowClear: true,
        },
        {
          dataIndex: 'flowapplicant',
          title: '流程申请人',
          type: DATA_ENTRY.SELECT,
          dataSource: selectApply,
          allowClear: true,
          filterOption: (
            input,
            option, //模糊搜索value 和 title
          ) => {
            return option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0 || option.props.value.toLowerCase().indexOf(input.toLowerCase()) >= 0;
          },
        },
      ],
      onQuery: (e) => {
        this.setState({ formData: e, isReset: false }, (e) => {
          this.searchData(e);
        });
      },
      onClear: () => {
        const { form } = this.props;
        const { formData } = this.state;
        form.resetFields();
        if (
          formData.startTime ||
          formData.endTime ||
          formData.flowName ||
          formData.securityName ||
          formData.securityType ||
          formData.flowState ||
          formData.poolWay ||
          formData.direction ||
          formData.flowapplicant
        ) {
          this.setState({ isReset: true });
        } else {
          this.setState({ isReset: false });
        }
      },
    };
    return (
      <ContentPackage
        title='券池审批'
        contentHtml={
          <div className={style.bodyAreas}>
            <div className='mainArea'>
              <AdvancedSearch {...searchProps} />
            </div>
            {this.tableRender()}
            {this.showModal()}
          </div>
        }
      />
    );
  }
}
export default connect(({ couponPoolApprovalM, loading, globalM }) => ({
  couponPoolApprovalM,
  loading: loading,
  globalM,
}))(CouponPoolApproval);
